<!--
 * @author  dumeng
新增/编辑答题活动
-->
<template>
  <section class="special-manage">
    <div class="manage-title">新增/编辑答题活动</div>

    <section class="manage-main">
      <el-form ref="form" v-loading="formloading" :model="form" :rules="rules" label-width="150px" class="main-form">
        <el-form-item label="活动类型" prop="classifyId">
          <el-radio-group v-model="form.classifyId">
            <el-radio v-for="(item, index) in dict.HDZXFXPC" :key="index" :label="item.dictValue">{{ item.dictName }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动图片" prop="imgId">
          <image-upload
            :key="upload.imagecropperKey"
            v-model="form.imgId"
            :preview-id="upload.viewId"
            :forever="true"
            :width="750"
            :view="upload.view"
            :height="480"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
            :is-oss="upload.isOss"
            @changeOssPath="
              (path) => {
                upload.viewId = path
              }
            "
          />
        </el-form-item>
        <el-form-item label="活动背景色" prop="bgImgId">
          <el-color-picker v-model="form.bgImgId" />
        </el-form-item>
        <el-form-item label="活动时间" required>
          <el-col :span="11">
            <el-form-item label prop="startTime">
              <el-date-picker
                v-model="form.startTime"
                type="datetime"
                :picker-options="pickeroptionsstart"
                placeholder="选择日期"
                style="width: 100%"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-form-item label prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="datetime"
                :picker-options="pickeroptionsend"
                placeholder="选择日期"
                style="width: 100%"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-form-item>
        <!-- <el-form-item label="排行榜样式" prop="rankingListStyle">
          <el-select v-model="form.rankingListStyle">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->
        <!-- <section v-if="form.rankingListStyle === '0'" class="rankImg">
          <div class="demo-image__preview">
            <el-image
              style="width: 100px; height: 100px"
              :src="require('../images/rankA.jpg')"
              :preview-src-list="[require('../images/rankA.jpg')]"
            />
          </div>
        </section> -->
        <!-- <section v-if="form.rankingListStyle === '1'" class="rankImg">
          <div class="demo-image__preview">
            <el-image
              style="width: 100px; height: 100px"
              :src="require('../images/rankB.jpg')"
              :preview-src-list="[require('../images/rankB.jpg')]"
            />
          </div>
        </section> -->
        <el-form-item label="活动说明" prop="remark">
          <tinymce v-if="showtinymce" v-model="form.remark" :is-oss="upload.isOss" :height="300" />
        </el-form-item>
        <el-form-item label="排行类型">
          <el-select v-model="form.rankingType" placeholder="请选择排行类型" style="width: 100%;">
            <el-option :key="1" value="1" label="总成绩排行" />
            <el-option :key="2" value="2" label="单次最高分排行" />
          </el-select>
        </el-form-item>
        <el-form-item label="展示排名数量" prop="rankLimitNum">
          <el-input
            v-model.number="form.rankLimitNum"
            placeholder="请输入排行榜展示人数"
            :disabled="numberType"
            style="width: 750px; margin-right: 20px"
          />
          <el-checkbox v-model="numberType">不限</el-checkbox>
        </el-form-item>
        <!-- 加入抽奖相关 -->
        <el-form-item label="是否关联抽奖" prop="isDraw">
          <el-radio-group v-model="form.isDraw">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="职工端是否展示">
          <el-radio-group v-model="form.isAppVisit">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.isDraw === '1'" label="每日抽奖条件" prop="drawChance">
          <el-input v-model.number="form.everydayNeedNum" placeholder="请输入" />
          <span style="color:red;">注：每日参与几次答题可获得抽奖机会</span>
        </el-form-item>
        <el-form-item v-if="form.isDraw === '1'" label="每日获取抽奖次数上限">
          <el-input
            v-model.number="form.everyDayLimitChance"
            placeholder="请输入每日抽奖次数"
            oninput="value=value.replace(/[^0-9]/g,'')"
            :disabled="meiri"
            style="width: 750px; margin-right: 20px"
          />
          <el-checkbox v-model="meiri">不限</el-checkbox>
        </el-form-item>
        <el-form-item v-if="form.isDraw === '1'" label="每日抽奖机会" prop="drawChance">
          <el-input v-model.number="form.drawChance" placeholder="请输入" />
          <span style="color:red;">注：每日参与答题可获得多少次抽奖机会</span>
        </el-form-item>
        <el-form-item v-if="form.isDraw === '1'" label="总抽奖机会" prop="drawChance">
          <el-input v-model.number="form.allDrawTimes" placeholder="请输入" />
        </el-form-item>
        <el-form-item v-if="form.isDraw === '1'" label="抽奖配置" prop="bigturntableId">
          <div>
            <el-button class="button-new-tag" size="small" @click="showInputRwys">抽奖配置</el-button>
          </div>
          <div>
            <el-tag v-if="dialogMultipleSelections.bigturntableName !== undefined" closable @close="handleCloses(dialogMultipleSelections)">
              {{ dialogMultipleSelections.bigturntableName || bigturntableName }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item v-if="form.isDraw === '1'" label="抽奖弹窗标题" prop="popTitle">
          <el-input v-model="form.popTitle" autosize placeholder="请输入" />
        </el-form-item>
        <el-form-item v-if="form.isDraw === '1'" label="抽奖弹窗引导按钮" prop="popButton">
          <el-input v-model="form.popButton" autosize placeholder="请输入" />
        </el-form-item>
        <el-form-item v-if="form.isDraw === '1'" label="抽奖弹窗样式选择" prop="popStyle">
          <el-select v-model="form.popStyle" autosize placeholder="请选择" style="width: 100%">
            <el-option v-for="item in popStyleList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-image style="width: 375px;margin-top: 10px;" :src="popStyleList[form.popStyle].imagesOss" />
        </el-form-item>
        <el-form-item v-if="form.isDraw === '1'" label="抽奖活动说明" prop="drawExplain">
          <el-input v-model="form.drawExplain" autosize type="textarea" placeholder="请输入" />
        </el-form-item>
        <!-- <el-form-item label="成功是否抽奖" prop="succIsBigturntable">
          <el-radio-group v-model="form.succIsBigturntable">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <!-- <el-form-item v-if="form.succIsBigturntable == 1" label="抽奖活动" prop="bigturntableId">
          <el-select v-model="form.bigturntableId" placeholder="请选择">
            <el-option v-for="item in lotterys" :key="item.value" :label="item.bigturntableName" :value="item.id" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="form.sort" placeholder="请输入排序号（值越大，越靠前）" />
        </el-form-item>
      </el-form>
    </section>

    <div class="manage-footer">
      <el-button style="padding: 8px 30px" @click="handleCancel">取消</el-button>
      <el-button style="padding: 8px 30px" type="primary" @click="handleSubmit">确定</el-button>
    </div>
    <!-- 选择转盘 -->
    <el-dialog title="选择抽奖配置" :visible.sync="dialogFormVisibles" center fullscreen :close-on-click-modal="false">
      <choose-prize
        ref="resetAll"
        v-loading.fullscreen.lock="fullscreenLoadings"
        :before-list="beforeLists"
        :bigturntable-id="form.bigturntableId"
        @userData="userDatas"
      />
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px" @click="dialogFormVisibles = false">取消</el-button>
        <el-button style="padding: 8px 30px" type="primary" @click="insertUsers()">确定</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import ChoosePrize from '@/views/activity/tphd/components/choosePrize'
import { specialText, int, doublescore, intwith, havaInt } from '@/utils/validate'
import ImageUpload from '@/components/ImageUpload'
import { getDictByCode, queryLottery, insert, update, get, getClassifyTree } from '../api/newSpecial'
import Tinymce from '@/components/Tinymce'
export default {
  name: 'SpecialManage',
  components: { ImageUpload, Tinymce, ChoosePrize },
  data() {
    return {
      popStyleList: [
        {
          id: 0,
          name: '样式一',
          imagesOss: 'https://bjttsx-yanshi.oss-cn-beijing.aliyuncs.com/1/22/12/02/221202cc96931db26743919206900e8a2f390d.png'
        },
        {
          id: 1,
          name: '样式二',
          imagesOss: 'https://bjttsx-yanshi.oss-cn-beijing.aliyuncs.com/1/22/12/02/22120231f566d987e046718fe2eeae498020b6.png'
        },
        {
          id: 2,
          name: '样式三',
          imagesOss: 'https://bjttsx-yanshi.oss-cn-beijing.aliyuncs.com/1/22/12/02/2212027a85a262f6da40b8ab08ff5f8788f276.png'
        },
        {
          id: 3,
          name: '样式四',
          imagesOss: 'https://bjttsx-yanshi.oss-cn-beijing.aliyuncs.com/1/22/12/02/221202d7f2d0d9c2cd40d1a474301bdae7e155.png'
        },
        {
          id: 4,
          name: '样式五',
          imagesOss: 'https://bjttsx-yanshi.oss-cn-beijing.aliyuncs.com/1/22/12/02/2212026bf78ddb405c4affa83fab281ba8cf02.png'
        },
        {
          id: 5,
          name: '样式六',
          imagesOss: 'https://bjttsx-yanshi.oss-cn-beijing.aliyuncs.com/1/22/12/02/221202827b3f4b16a54addb0ae0fdc1d0ac910.png'
        },
        {
          id: 6,
          name: '样式七',
          imagesOss: 'https://bjttsx-yanshi.oss-cn-beijing.aliyuncs.com/1/22/12/02/221202ff3f9084d3bb4f1abb6ca173f24a253b.png'
        },
        {
          id: 7,
          name: '样式八',
          imagesOss: 'https://bjttsx-yanshi.oss-cn-beijing.aliyuncs.com/1/22/12/02/2212022fc3e4e4f9484ceabea370fab0c5e407.png'
        }
      ],
      dialogMultipleSelections: {},
      beforeLists: [],
      fullscreenLoadings: false,
      dialogFormVisibles: false,
      state: 'create',
      unlimited: true, // 每日积分是否上限
      formloading: false,
      showtinymce: false,
      numberType: false,
      meiri: true,
      showClassify: false,
      options: [
        {
          value: '0',
          label: '排行榜样式一'
        },
        {
          value: '1',
          label: '排行榜样式二'
        }
      ],
      classifyOptions: [],
      form: {
        popTitle: '',
        popButton: '',
        popStyle: 0,
        allDrawTimes: 0,
        everydayNeedNum: 0,
        bigturntableId: '',
        drawChance: 0,
        drawExplain: '',
        isDraw: '0',
        id: '',
        classifyId: '', // type
        name: '',
        bgImgId: '',
        imgId: '',
        activityBackgroundImg: 'no',
        remark: '',
        // rankingListStyle: '0',
        startTime: '',
        endTime: '',
        sort: '',
        succIsBigturntable: '0',
        bigturntableId: '',
        rankLimitNum: '', // 统计人数
        isAppVisit: '1',
        everyDayLimitChance: '',
        rankingType: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { validator: specialText, trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '长度在 1 到 50 个字符',
            trigger: 'blur'
          }
        ],
        remark: [{ required: true, message: '请输入活动说明', trigger: 'blur' }],
        // rankingListStyle: [
        //   { required: true, message: '请选择排行榜样式 ', trigger: 'change' }
        // ],
        bgImgId: [{ required: true, message: '请选择活动背景色', trigger: 'blur' }],
        imgId: [{ required: true, message: '请上传活动图片', trigger: 'blur' }],
        activityBackgroundImg: [{ required: true, message: '请上传活动背景图片', trigger: 'blur' }],
        startTime: [{ required: true, message: '请选择开始日期', trigger: 'blur' }],
        endTime: [{ required: true, message: '请选择结束日期', trigger: 'blur' }],
        rankLimitNum: [
          // { required: false, trigger: 'blur' },
          { trigger: 'blur', validator: havaInt }
        ],
        succIsBigturntable: [
          {
            required: true,
            message: '请选择答题成功是否抽奖',
            trigger: 'blur'
          }
        ],
        bigturntableId: [{ required: true, message: '请选择抽奖活动', trigger: 'blur' }]
      },
      classifyProps: {
        label: 'classifyName',
        value: 'id',
        checkStrictly: true
      },
      upload: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false
      },
      upload4bg: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      lotterys: [],
      type: 1,
      dict: {
        HDZXFXPC: [] // type
      },
      pickeroptionsstart: {
        disabledDate: (time) => {
          if (this.form.endTime) {
            return time.getTime() > new Date(this.form.endTime).getTime()
          }
        }
      },
      pickeroptionsend: {
        disabledDate: (time) => {
          if (this.form.startTime) {
            return time.getTime() < new Date(this.form.startTime).getTime()
          }
        }
      }
    }
  },
  watch: {
    'form.succIsBigturntable': {
      handler(newName, oldName) {
        if (newName) {
          if (this.form.bigturntableId === -1 || this.form.bigturntableId === '-1') {
            this.form.bigturntableId = ''
          }
        }
      },
      immediate: true,
      deep: true
    },
    'form.classifyId': {
      handler(newName, oldName) {
        if (this.$refs.classify) {
          this.$refs.classify.dropDownVisible = false
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.state = this.$route.query.type === 'c' ? 'create' : 'update'
    // this.getLottery()
    for (const key in this.dict) {
      this.getDict(key)
    }
    if (this.$route.query.type === 'u') {
      if (this.$route.query.i) {
        this.getData(this.$route.query.i)
      } else {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
      }
    } else {
      this.showtinymce = true
      this.showClassify = true
    }
  },
  methods: {
    handleCloses(dialogMultipleSelections) {
      this.dialogMultipleSelections = {}
      this.form.bigturntableId = ''
    },
    // 确定选择抽奖配置
    insertUsers() {
      if (JSON.stringify(this.dialogMultipleSelections) === '{}') {
        this.$message({
          message: '请选择抽奖配置',
          type: 'warning'
        })
      } else {
        this.$set(this.form, 'bigturntableId', this.dialogMultipleSelections.id)
        this.dialogListLoadings = true
        this.dialogFormVisibles = false
      }
    },
    // 选择人物元素
    userDatas(val) {
      this.dialogMultipleSelections = val
    },
    // 选择转盘
    showInputRwys() {
      this.dialogFormVisibles = true
    },
    /**
     * 获取字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((res) => {
            this.dict[code] = res.data.data && res.data.data.length > 0 ? res.data.data[0].list : []
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    getLottery() {
      return new Promise((resolve, reject) => {
        queryLottery({ status: 'BIGTSTATUS01' })
          .then((res) => {
            this.lotterys = res.data.data || []
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    handleSubmit() {
      this.state === 'create' ? this.createData() : this.updateData()
    },

    handleCancel() {
      this.$router.push({ path: this.$filterPath('index') })
    },

    /*
     * 新增
     * */
    createData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          if (this.numberType) {
            this.form.rankLimitNum = -9999
          }
          const params = Object.assign({}, this.form)
          params['bigturntableId'] = this.form.succIsBigturntable === 0 || this.form.succIsBigturntable === '0' ? '-1' : this.form.bigturntableId
          if (this.meiri === true) {
            params.everyDayLimitChance = -1
          }
          return new Promise((resolve, reject) => {
            insert(params)
              .then(() => {
                loading.close()
                this.$message({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 1500
                })
                this.$router.push({ path: this.$filterPath('index') })
              })
              .catch((error) => {
                reject(error)
                loading.close()
              })
          })
        }
      })
    },

    /**
     * 编辑提交
     */
    updateData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          if (this.numberType) {
            this.form.rankLimitNum = -9999
          }
          const params = Object.assign({}, this.form)
          params['bigturntableId'] = this.form.succIsBigturntable === 0 || this.form.succIsBigturntable === '0' ? '-1' : this.form.bigturntableId
          if (this.meiri === true) {
            params.everyDayLimitChance = -1
          }
          return new Promise((resolve, reject) => {
            update(params)
              .then(() => {
                loading.close()
                this.dialogFormVisible = false
                this.$message({
                  title: '成功',
                  message: '编辑成功',
                  type: 'success',
                  duration: 2000
                })
                this.$router.push({ path: this.$filterPath('index') })
              })
              .catch((error) => {
                reject(error)
                loading.close()
              })
          })
        }
      })
    },

    cancel() {
      this.$router.push({ path: this.$filterPath('index') })
    },

    /**
     * 获取详情
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id })
          .then((res) => {
            loading.close()
            const data = res.data.data
            for (const key in this.form) {
              if (key === 'imgId') {
                this.form[key] = data.imgId || ''
                this.upload.viewId = data.imgIdUrl || ''
              } else if (key === 'rankLimitNum') {
                if (data['rankLimitNum'] === -9999) {
                  this.form.rankLimitNum = ''
                  this.numberType = true
                  this.disabled = true
                } else {
                  this.form[key] = data[key]
                }
              } else if (key === 'everyDayLimitChance') {
                this.meiri = +data[key] === -1
                this.form[key] = +data[key] === -1 ? '' : data[key]
              } else {
                this.form[key] = data[key]
              }
            }
            this.$set(this.form, 'popStyle', this.form.popStyle ? this.form.popStyle : 0)
            this.$set(this, 'dialogMultipleSelections', {
              bigturntableName: res.data.data.bigturntableName,
              id: res.data.data.bigturntableId
            })
            this.showtinymce = true
            this.$nextTick(() => {
              this.showClassify = true
            })
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    }
  }
}
</script>
<style lang="scss">
.special-manage {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;
  .manage-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;
    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .manage-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;
    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }
    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }
    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }
    &:hover {
      overflow: auto;
    }
  }

  .main-form {
    width: 1000px !important;
    margin: 0 auto;
    .line {
      text-align: center;
    }
    .form-card {
      margin-top: 20px;
      .el-card__body {
        max-width: 90%;
        margin: 0 auto;
      }
    }
    .rankImg {
      width: 100px;
      height: 100px;
      margin-left: 150px;
      margin-bottom: 20px;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .manage-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
}
</style>
